package com.javaee.web.servlet;
import java.io.IOException;
import java.util.List;

import com.javaee.ejb.entity.Conversation;
import com.javaee.ejb.entity.ConversationMessage;
import com.javaee.ejb.jms.remote.ConversationMessageQueueBrowserRemote;
import com.javaee.ejb.session.remote.ConversationManagerRemote;
import com.javaee.ejb.session.remote.ConversationMessageManagerRemote;
import com.javaee.web.HttpServletBase;
import com.javaee.web.SiteParameters;

import javax.ejb.EJB;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CortexTalkServlet
 */
public class CortexTalkServlet extends HttpServletBase implements Servlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private ConversationManagerRemote conversationManager;
	@EJB
	private ConversationMessageManagerRemote messageManager;
	@EJB
	private ConversationMessageQueueBrowserRemote queueBrowser;

	/**
	 * @see HttpServletBase#HttpServletBase()
	 */
	public CortexTalkServlet() {
		super();
	}

	@Override
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int conversationId;
		try {
			conversationId = Integer.parseInt(request
					.getParameter("conversationId"));
		} catch (Exception e) {
			throw new ServletException(e.getMessage());
		}

		// Chargement de la conversation
		Conversation conversation = conversationManager
				.getByIdWithDependencies(conversationId);
		request.setAttribute("conversation", conversation);

		// Chargement des derniers messages presents dans la file
		List<ConversationMessage> lastMessageList = queueBrowser
				.getLastMessage(conversationId, SiteParameters.nbMessageMax);
		request.setAttribute("lastMessageList", lastMessageList);

		// Chargement de tous les messages de la conversation
		List<ConversationMessage> messageHistoList = messageManager
				.getListByConversationId(conversationId);
		request.setAttribute("messageHistoList", messageHistoList);

		loadJSP(SiteParameters.getPagePath("cortexTalk"), request, response);
	}
}
